package com.tj.jinzao.widgets;

import android.content.Context;
import android.text.InputFilter;
import android.text.Spanned;

import com.tj.jinzao.utils.ToastUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MaxTextLengthFilterFH implements InputFilter {
    final Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
            Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);

    private int mMaxLength;
    private String name;
    //构造方法中传入最多能输入的字数
    public MaxTextLengthFilterFH(int max, Context context, String name) {
        mMaxLength = max;
        this.name=name;
        this.context=context;
    }
    private Context context;
    public MaxTextLengthFilterFH(Context context){
        this.context=context;
    }

    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        int keep = mMaxLength - (dest.length() - (dend - dstart));
        if (keep < (end - start)) {
            ToastUtils.showToast(context,name);
        }
        Matcher emojiMatcher = emoji.matcher(source);
        //禁止特殊符号
        String speChat = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Pattern pattern = Pattern.compile(speChat);
        Matcher matcher = pattern.matcher(source.toString());
        //禁止输入空格
        if (source.equals(" ") || source.toString().contentEquals("\n")) {
            return "";
            //禁止输入表情
        } else if (emojiMatcher.find()) {
            return "";
        } else if (matcher.find()) {
            return "";
        } else  if (keep <= 0) {
            return "";
        } else if (keep >= end - start) {
            return null;
        } else {
            return source.subSequence(start, start + keep);
        }

    }
}
